<template>
    <el-dialog v-model="dialogVisible" :title="title" width="500px">
        <div>
            <el-form
                ref="formModelRef"
                :model="formModel"
                :rules="rules"
                label-width="auto"
                class="demo-formModel"
                :size="formSize"
                status-icon
            >
                <el-form-item label="新密码" prop="password">
                    <el-input show-password v-model="formModel.password" />
                </el-form-item>
                <el-form-item label="确认密码" show-password prop="re_password">
                    <el-input show-password v-model="formModel.re_password" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input type="number" v-model.number="formModel.phone" />
                </el-form-item>

                <el-form-item label="验证码" prop="code">
                    <el-input
                        v-model.number="formModel.code"
                        type="number"
                        style="width: 65%"
                        placeholder="请输入验证码"
                    />
                    <el-button
                        type="primary"
                        @click="sendSms"
                        style="margin-left: 20px"
                        :disabled="seconds > 0"
                    >
                        <span v-if="seconds > 0">{{ seconds }}秒后重发</span>
                        <span v-else>发送验证码</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(formModelRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(formModelRef)">重置</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from "vue"; // 添加 onUnmounted 导入
import { ElMessage } from "element-plus";
import { resetPwdSms } from "@/api/sms";
import { resetPwdByPhone } from "@/api/user";

const props = defineProps({
    showDialog: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: "",
    },
});

const emit = defineEmits(["update:showDialog"]);
const dialogVisible = computed({
    get: () => props.showDialog,
    set: (val) => emit("update:showDialog", val),
});

const formSize = ref("default");
const formModelRef = ref();
const formModel = reactive({
    password: "",
    re_password: "",
    phone: "",
    code: "",
});

const pwdRules = [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 30, message: "密码的长度至少是6位，最多是30位", trigger: "blur" },
    {
        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,30}$/,
        message: "密码必须包含大小写字母、数字和特殊字符",
        trigger: "blur",
    },
];

const rules = reactive({
    password: pwdRules,
    re_password: [
        ...pwdRules,
        {
            validator: (rule, value, callback) => {
                if (value !== formModel.password) {
                    callback(new Error("两次输入的密码不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
    phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { pattern: /^1[3456789]\d{9}$/, message: "手机格式不正确", trigger: "blur" },
    ],
    code: [
        { required: true, message: "请输入验证码", trigger: "blur" },
        { pattern: /^\d{6}$/, message: "请查看验证码，必须是6位数字", trigger: "blur" },
    ],
});

const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log("submit!");
            // 提交表单
            resetPwdByPhone({
                ...formModel
            }).then((res) => {
                // console.log("res:", res);
                if (res.code == 1) {
                    dialogVisible.value = false;
                    ElMessage.success(res.msg || "密码修改成功");
                } else {
                    ElMessage.error(res.msg || "密码修改失败");
                }
            })
            
        } else {
            // console.log("error submit!", fields);
        }
    });
};

const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
};

// 验证码倒计时相关
const seconds = ref(0);
let timer = null;

// 发送验证码
const sendSms = () => {
    // console.log("发送验证码");
    if (!/^1[3456789]\d{9}$/.test(formModel.phone)) {
        ElMessage.error("请输入手机号");
        return;
    }

    if (formModel.phone.toString().length !== 11) {
        ElMessage.error("请输入正确的手机号");
        return;
    }

    resetPwdSms({ phone: formModel.phone }).then((res) => {
        // console.log("res:", res);
        if (res.code == 1) {
            seconds.value = 60;
            if (timer) clearInterval(timer);
            timer = setInterval(() => {
                seconds.value--;
                if (seconds.value <= 0) {
                    clearInterval(timer);
                    timer = null;
                }
            }, 1000);
            ElMessage.success(res.msg || "发送成功");
        } else {
            ElMessage.error(res.msg || "发送失败");
        }
    });
};

// 组件卸载时清理定时器
onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
    }
});
</script>
